package top.chatgqt.SmartChargeStation.mqtt.client.api;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.chatgqt.SmartChargeStation.mqtt.client.conf.MqttProps;
import top.chatgqt.SmartChargeStation.mqtt.client.service.MqttService;
import top.chatgqt.SmartChargeStation.mqtt.client.utils.TransformerUtils;
import top.chatgqt.SmartChargeStation.protocol.mqtt.message.ChargePayload;

@RestController
@Slf4j
public class SendApi {

    @Resource
    private MqttProps props;

    @Resource
    private MqttService gateway;

    /**
     * 发送MQTT消息（payload）
     */
    @RequestMapping(path = "/mqtt/send", method = RequestMethod.POST)
    String doSend(@RequestBody ChargePayload message) {

        /* **********************
         *
         * 16进制相比于json：
         *
         * 1. 比Json更加紧凑，传输效率更高，占用带宽更少
         * 2. 比Json编解码的速度更快
         * 3. 嵌入式硬件设备内存比较小，16进制比Json占用内存更少
         * 4. 嵌入式硬件设备性能不高，16进制比Json对于设备的计算能力要求更低
         *
         *
         *  如何发送16进制报文：
         *
         * 思路：将16进制的字符串转换为字节组
         *      MQTT客户端将字节数组发送出去
         *
         * 1. 将 ChargePayload 转换为 16进制
         * 2. 将16进制的字符串转化为字节数组
         *
         * *********************/

        String hex = TransformerUtils.objectToHex(message);
        byte[] bytes = TransformerUtils.hexToBytes(hex);

        Message<byte[]> msg = MessageBuilder.withPayload(bytes).build();

        gateway.send(props.getTopic(), msg);

        return "send mqtt message success !";
    }
}
